<template>
  <Card dis-hover :bordered="false">
    <Row>
      <Col span="22">
        <Form inline :label-width="0">
          <FormItem>
            <Input
              placeholder="请输入姓名或手机号"
              v-model="params.keyword"
              @on-clear="searchData"
              @on-enter="searchData"
              clearable
            />
          </FormItem>
          <FormItem>
            <Select
              placeholder="请选择项目"
              v-model="params.project_id"
              multiple
              :filterable="projectList.length >= 10"
              clearable
              @on-change="searchData"
            >
              <Option
                v-for="item in projectList"
                :value="item.value"
                :key="item.value"
                >{{ item.label }}</Option
              >
            </Select>
          </FormItem>
          <FormItem>
            <TreeSelect
              v-width="150"
              placeholder="部门"
              v-model="params.department_id"
              :data="departmentList"
              @on-change="searchData"
              @on-clear="clearDep"
              clearable
            />
          </FormItem>
          <FormItem>
            <Select
              placeholder="请选择角色"
              v-model="params.role_id"
              multiple
              :filterable="roleList.length >= 10"
              clearable
              @on-change="searchData"
            >
              <Option
                v-for="item in roleList"
                :value="item.value"
                :key="item.value"
                >{{ item.label }}</Option
              >
            </Select>
          </FormItem>
          <FormItem>
            <Select
              placeholder="请选择状态"
              v-model="params.status"
              clearable
              @on-change="searchData"
            >
              <Option
                v-for="item in stateList"
                :value="item.value"
                :key="item.value"
                >{{ item.label }}</Option
              >
            </Select>
          </FormItem>
        </Form>
      </Col>
      <Col span="2" style="text-align: right">
        <Button
          type="primary"
          @click="handleAdd"
          v-hasC="{
            name: 'v1-member-create',
            flag: 'v1/member/create',
          }"
          >新增</Button
        >
      </Col>
    </Row>

    <Table
      :columns="columns"
      :data="list"
      :loading="loading"
      @on-sort-change="sortChange"
      :max-height="tableHeigth"
    >
      <template #department="{ row }">
        <span>{{ row.department_name_arr.join(" / ") }}</span>
      </template>
      <template #project="{ row }">
        <span>{{ row.project_name_arr.join(" , ") }}</span>
      </template>
      <template #role="{ row }">
        <span>{{ row.role_name_arr.join(" , ") }}</span>
      </template>
      <template #status_str="{ row }">
        <Badge
          status="success"
          :text="row.status_str"
          v-if="row.status_str === '正常'"
        />
        <Badge status="error" :text="row.status_str" v-else />
      </template>
      <template #action="{ row }">
        <a
          @click="handleEdit(row)"
          v-hasC="{
            name: 'v1-member-update',
            flag: 'v1/member/update',
          }"
          >编辑</a
        >
        <Divider
          type="vertical"
          v-hasC="{
            name: 'v1-member-update',
            flag: 'v1/member/update',
          }"
        />
        <a
          @click="handleDel(row.id)"
          class="del"
          v-hasC="{
            name: 'v1-member-delete',
            flag: 'v1/member/delete',
          }"
          >删除</a
        >
      </template>
    </Table>
    <Page
      class="ivu-mt-16"
      :total="total"
      :modelValue="params.current"
      :page-size="params.size"
      :page-size-opts="pageOpts"
      show-total
      show-sizer
      @on-change="changePage"
      @on-page-size-change="changepageSize"
    />
    <Modal
      :mask-closable="false"
      v-model="addModal"
      :title="edit ? '新增' : '编辑'"
      :footer-hide="true"
      :draggable="true"
    >
      <Form ref="create" :model="memberInfo" :rules="rules" :label-width="100">
        <FormItem label="用户名" prop="username" required>
          <Input
            v-model="memberInfo.username"
            placeholder="请输入用户名"
            :maxlength="30"
          />
        </FormItem>
        <FormItem label="密码" prop="password">
          <Input
            v-model="memberInfo.password"
            placeholder="请输入密码"
            :maxlength="30"
          />
        </FormItem>
        <FormItem
          label="手机号"
          prop="mobile"
          :rules="{
            required: true,
            message: '请输入正确的联系号码',
            pattern: /^1\d{10}$/,
            trigger: 'blur',
          }"
        >
          <Input
            v-model="memberInfo.mobile"
            type="tel"
            placeholder="请输入手机号"
            @input="memberInfo.mobile = memberInfo.mobile.slice(0, 11)"
          />
        </FormItem>
        <FormItem label="项目" prop="project_ids" required>
          <Select
            placeholder="请选择项目"
            v-model="memberInfo.project_ids"
            multiple
            :filterable="editProjectList.length >= 10"
            clearable
          >
            <Option
              v-for="item in editProjectList"
              :disabled="item.disabled == 1"
              :value="parseInt(item.value)"
              :key="item.value"
              >{{ item.label }}</Option
            >
          </Select>
        </FormItem>
        <FormItem label="部门" prop="department_ids" required>
          <TreeSelect
            placeholder="请选择部门"
            v-model="memberInfo.department_ids"
            :data="editDepartmentList"
            :transfer="true"
            @on-change="changeDep"
            :disabled="allowEdit"
          />
        </FormItem>
        <FormItem label="角色" prop="role_ids" required>
          <Select
            placeholder="请选择角色"
            v-model="memberInfo.role_ids"
            multiple
            :filterable="editRoleList.length >= 10"
            :disabled="allowEdit"
          >
            <Option
              v-for="item in editRoleList"
              :disabled="item.disabled == 1"
              :value="parseInt(item.value)"
              :key="item.value"
              >{{ item.label }}</Option
            >
          </Select>
        </FormItem>
        <FormItem label="岗位" prop="job_id" required>
          <Select
            placeholder="请选择岗位"
            v-model="memberInfo.job_id"
            :filterable="editJobList.length >= 10"
          >
            <Option
              v-for="item in editJobList"
              :value="parseInt(item.value)"
              :key="item.value"
              >{{ item.label }}</Option
            >
          </Select>
        </FormItem>
        <FormItem label="状态" prop="status">
          <Switch v-model="memberInfo.status" />
        </FormItem>
      </Form>
      <div slot="footer" style="text-align: right">
        <Button type="default" @click="addModal = false">取消</Button>
        <Button
          type="primary"
          @click="ok"
          style="margin-left: 10px"
          :loading="btnLoading"
          >确定</Button
        >
      </div>
    </Modal>
  </Card>
</template>
<script>
import {
  memberList,
  createMember,
  deleteMember,
  memberInfo,
  updateMember,
  memberCondition,
  changeDepInfo,
} from "@api/person.js";
export default {
  name: "person",
  data() {
    return {
      tableHeigth: document.body.clientHeight - 280,
      addModal: false,
      edit: true,
      loading: false,
      btnLoading: false,
      stateList: [],
      projectList: [],
      departmentList: [],
      roleList: [],
      editProjectList: [],
      editRoleList: [],
      editDepartmentList: [],
      editJobList: [],
      params: {
        keyword: "",
        current: 1,
        size: 10,
        status: "",
        role_id: [],
        project_id: [],
        department_id: "",
        order_column: "",
        order_sort: "",
      },
      total: 0,
      pageOpts: [10, 20, 30, 40],
      columns: [
        {
          key: "id",
          title: "ID",
          width: 80,
        },
        {
          key: "username",
          title: "用户名",
          width: 100,
        },
        {
          key: "mobile",
          title: "手机号",
          width: 125,
        },
        {
          slot: "project",
          title: "项目",
          minWidth: 150,
        },
        {
          slot: "department",
          title: "部门",
          minWidth: 150,
        },
        {
          key: "job_name",
          title: "岗位",
          width: 100,
        },
        {
          slot: "role",
          title: "角色",
          minWidth: 150,
        },
        {
          slot: "status_str",
          title: "状态",
          width: 80,
        },
        {
          key: "last_time_str",
          title: "最后登录时间",
          width: 150,
          sortable: "custom",
        },
        {
          slot: "action",
          title: "操作",
          width: 110,
          fixed: "right",
        },
      ],
      list: [],
      memberInfo: {
        id: "",
        username: "",
        mobile: "",
        password: "",
        project_ids: [],
        department_ids: "",
        role_ids: [],
        job_id: "",
        status: true,
      },
      rules: {
        username: [{ required: true, message: "请输入用户名" }],
        project_ids: [
          {
            required: true,
            message: "请选择项目",
            type: "array",
            min: 1,
            trigger: "change",
          },
        ],
        department_ids: [
          {
            required: true,
            message: "请选择部门",
          },
        ],
        role_ids: [
          {
            required: true,
            message: "请选择角色",
            type: "array",
            min: 1,
            trigger: "change",
          },
        ],
        job_id: [{ required: true, message: "请选择岗位" }],
      },
      allowEdit: false,
    };
  },
  mounted() {
    this._select();
    this.getData();
  },
  methods: {
    _select() {
      memberCondition()
        .then((res) => {
          this.projectList = res.project;
          this.roleList = res.role;
          this.stateList = res.status;
          this.departmentList = this.changeData(res.department);
        })
        .catch(() => {});
    },
    searchData() {
      this.params.current = 1;
      this.getData();
    },
    clearDep() {
      this.params.department_id = "";
      this.searchData();
    },
    sortChange(e) {
      this.params.order_column = e.key.replace(/_str$/, "");
      this.params.order_sort = e.order;
      this.getData();
    },
    //切换page
    changePage(index) {
      this.params.current = index;
      this.getData();
    },
    changepageSize(val) {
      this.params.size = val;
      this.getData();
    },

    handleDel(index) {
      this.$Modal.confirm({
        title: "删除提示",
        content: "是否确认删除此条记录，删除后不可恢复",
        onOk: () => {
          deleteMember({ id: index })
            .then(() => {
              this.$Message.success("删除成功");
              this.getData();
            })
            .catch(() => {});
        },
      });
    },
    changeData(list) {
      list.forEach((item) => {
        item.title = item.department_name;
        item.value = +item.id;
        item.expand = true;
        if (item.children && item.children.length > 0) {
          this.changeData(item.children);
        }
      });
      return list;
    },
    changeDep(e) {
      if (e) {
        let params = {
          department_id: [e],
          role_id: this.memberInfo.role_ids,
        };
        changeDepInfo(params).then((res) => {
          this.editRoleList = res.condition.role;
          this.memberInfo.role_ids = res.role_id;
        });
      }
    },
    handleAdd() {
      this.allowEdit = false;
      memberInfo({ id: 0 })
        .then((res) => {
          this.editProjectList = res.condition.project;
          this.editRoleList = res.condition.role;
          this.editDepartmentList = this.changeData(res.condition.department);
          this.editJobList = res.condition.job;
          this.memberInfo = {
            id: "",
            username: "",
            mobile: "",
            password: "",
            project_ids: [],
            department_ids: "",
            role_ids: [],
            job_id: "",
            status: true,
          };
          this.$nextTick(() => {
            this.$refs.create.resetFields();
          });
        })
        .catch(() => {});

      this.addModal = true;
      this.edit = true;
    },
    handleEdit(info) {
      this.memberInfo = {
        id: "",
        username: "",
        mobile: "",
        password: "",
        project_ids: [],
        department_ids: "",
        role_ids: [],
        job_id: "",
        status: true,
      };
      this.$refs.create.resetFields();
      memberInfo({ id: info.id })
        .then((res) => {
          this.memberInfo = {
            id: res.id,
            username: res.username,
            mobile: res.mobile,
            password: res.password ? res.password : "",
            project_ids: res.project_id,
            department_ids: res.department_id[0],
            role_ids: res.role_id,
            job_id: res.job_id,
            status: res.status == 1 ? true : false,
          };
          this.editProjectList = res.condition.project;
          this.editRoleList = res.condition.role;
          this.editDepartmentList = this.changeData(res.condition.department);
          this.editJobList = res.condition.job;
          this.allowEdit = res.condition.department_disabled;
        })
        .catch(() => {});
      this.addModal = true;
      this.edit = false;
    },
    getData() {
      this.loading = true;
      const params = {
        pageSize: this.params.size,
        page: this.params.current,
        status: this.params.status,
        keyword: this.params.keyword,
        project_id: this.params.project_id.join(","),
        role_id: this.params.role_id.join(","),
        department_id: this.params.department_id,
        order_column: this.params.order_column,
        order_sort: this.params.order_sort,
      };
      memberList(params)
        .then((res) => {
          this.list = res.list;
          this.total = res.total;
          this.loading = false;
        })
        .finally(() => {
          this.loading = false;
        });
    },
    addMember() {
      this.btnLoading = true;
      const params = {
        username: this.memberInfo.username,
        mobile: this.memberInfo.mobile,
        password: this.memberInfo.password,
        project_ids: this.memberInfo.project_ids,
        department_ids: [this.memberInfo.department_ids],
        role_ids: this.memberInfo.role_ids,
        job_id: this.memberInfo.job_id,
        status: this.memberInfo.status ? 1 : 0,
      };
      if (this.edit) {
        createMember(params)
          .then((res) => {
            this.$Message.success("添加成功");
            this.addModal = false;
            this.btnLoading = false;
            this.params.current = 1;
            this.getData();
          })
          .catch(() => {
            this.btnLoading = false;
          });
      } else {
        updateMember(Object.assign({}, params, { id: this.memberInfo.id }))
          .then((res) => {
            this.$Message.success("编辑成功");
            this.addModal = false;
            this.btnLoading = false;
            this.getData();
          })
          .catch(() => {
            this.btnLoading = false;
          });
      }
    },
    ok() {
      this.$refs.create.validate((valid) => {
        if (valid) {
          this.addMember();
        } else {
          this.addModal = true;
          // this.$Message.error('填写错误，保存失败！')
          return;
        }
      });
    },
  },
};
</script>
